#!/bin/bash

chmod -R 777 /opt/jdk1.8.0_202/bin
APP_NAME=${contextPath}

APP_PATH=/opt/${contextPath}/${contextPath}.jar


JAVA_HOME=/opt/jdk1.8.0_202

JAVA_OPTS="-Xmx512m -Xms512m -XX:MaxMetaspaceSize=256m"

APP_PORT=8085
APP_ENV=prod

function start() {
    PID=$(ps -ef | grep ${contextPath}.jar | grep -v grep | awk '{print $2}')
    if [[ -n "$PID" ]]; then
        echo "$APP_NAME is already running with PID $PID."
        exit 1
    fi
    echo "Starting $APP_NAME..."

    rm -f nohup.out

    nohup $JAVA_HOME/bin/java $JAVA_OPTS -Dserver.port=$APP_PORT -Dspring.profiles.active=$APP_ENV -jar $APP_PATH 2>&1 &

    echo "$APP_NAME started."
}

function restart() {
    echo "Restarting $APP_NAME..."

    stop

    sleep 5

    start

    echo "$APP_NAME restarted."
}

function stop() {
    echo "Stopping $APP_NAME..."

    PID=`ps -ef | grep $APP_NAME | grep -v grep | awk '{print $2}'`
    if [[ -n "$PID" ]]; then
        kill -9 $PID
    fi

    echo "$APP_NAME stopped."
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac

exit 0
